<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <script src="../lib/vue2.js"></script>
  </head>
  <body>
    <div id="box">
      <!-- 在开发中经常会碰到需要组件之间交流的情况 -->
      <!-- 两种简单的组件传值情况 -->
      <!-- 1.父传子，直接通过给标签附上属性值配合props可以实现 -->
      <my-com mymes="父元素传来的信息"></my-com>
      <!-- 2.子传父，通过定义事件和$emit触发 -->
      <!-- 子组件中定义触发myevent，在父组件中调用handleEvent handleEvent定义在父组件的methods中 -->
      <my-com @myevent="handleEvent"></my-com>
      <div>{{mesToPar}}</div>
    </div>

    <script>
      // 创建自定义组件
      Vue.component("myCom", {
        props: {
          mymes: {
            type: String,
            default: "",
          },
        },

        // mounted() {
        //   this.$emit("myevent", "子元素传来的值");
        // },

        template: ` <div>
            <h1>传值--{{mymes}}</h1><button @click="handleClick">子传父</button>
        </div>`,

        methods: {
          handleClick() {
            this.$emit("myevent", "子元素传来的值");
          },
        },
      });

      let vm = new Vue({
        el: "#box",
        data: {
          mesToPar: "",
        },
        methods: {
          handleEvent(data) {
            this.mesToPar = data;
          },
        },
      });
    </script>
  </body>
</html>
